<?php
session_start();
// 数据库连接配置
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接
if ($conn->connect_error) {
    die("连接失败: ". $conn->connect_error);
}

// 注册用户
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["register"])) {
    $newUsername = $_POST["newUsername"];
    $newPassword = $_POST["newPassword"];
    $captcha = $_POST["captchaRegister"];

    // 验证验证码
    if ($captcha!== $_SESSION["captcha"]) {
        echo "验证码错误";
        exit;
    }

    // 检查用户名是否已存在
    $checkSql = "SELECT * FROM users WHERE username = '$newUsername'";
    $checkResult = $conn->query($checkSql);
    if ($checkResult->num_rows > 0) {
        echo "用户名已存在，请选择其他用户名";
        exit;
    }

    // 对密码进行加密
    $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);

    // 插入新用户到数据库
    $sql = "INSERT INTO users (username, password) VALUES ('$newUsername', '$hashedPassword')";
    if ($conn->query($sql) === TRUE) {
        echo "注册成功";
    } else {
        echo "Error: ". $sql. "<br>". $conn->error;
    }
}

$conn->close();
?>